/**
 * jquery fn pager
 * 结构:
 * <div id=''>
 * 		<span class="btn_p">Prev</span> 
 * 		<strong>1</strong>
 * 		<a href="#" page="2">2</a>
 * 		<a href="#" page="3">3</a>...
 * 		<a href="#" class="btn_n" page="3">Next</a>
 * </div>
 * @param
 * options = {
 		urlFormat: '/hello/world/{page}', //required
     	prevClass: 'btn_p',
		nextClass: 'btn_n',	    
	    change: function(page){				
		}
 * }
 * @author  tanggf
 */
(function($){
	$.fn.pager = function(options){
		//default setting
		options = $.extend({			
			prevClass: 'btn_p',
			nextClass: 'btn_n',			
			change: function(page){				
			}
		}, options);
		
		return this.each(function(){
			_get_pager_(this, options);
		});	
	};
	
	function _get_pager_(ele, options){
		var $this = $(ele);
		var obj = $this.data("_wt_pager_");
		if( ! obj){
			obj = new _pager_(ele, options);
			$this.data("_wt_pager_", obj);
		}
		return obj;
	}
	
	function _pager_(ele, options){
		this.$ele = $(ele);
		this.options = options;
		this._init_();
	}
	
	_pager_.prototype = {
		_init_: function(){	
			this.urlFormat =this.options.urlFormat || 'javascript:;';
			this.currPage = parseInt(this.$ele.children("strong").attr("page")) || 1;			
			this.pageCount = this.$ele.children("a").length;
					
			this._bind_events();
		},
		
		_bind_events: function(){
			var self = this;
			this.$ele.children("a").click(function(){
				var page = parseInt($(this).attr("page"));
				self.currPage = page;
				self.options.change(page);
				
				self._rebuild_pager();
				return false;
			});
		},
		
		_rebuild_pager: function(){
			var minCount = 10;
			var page = this.currPage;
			var start = page - 5;
			var end = page + 4;			
			if(start < 1){
				start = 1;
				end = page + 9;
			}
			
			if(end > this.pageCount){
				end = this.pageCount;
			}
			
			var len = end - start + 1;
			if(len < minCount){
				start -= minCount - len;
				if(start < 1){
					start = 1;
				}
			}
			
			var aa = [];
			if(page > 1){
				var a = this._build_a(page - 1, "Prev", this.options.prevClass);
				aa.push(a);				
			}else{
				aa.push("<span class='" + this.options.prevClass + "'>Prev</span>");
			}
			
			for ( var num = start; num <= end; num++) {
				if(num == page){
					aa.push("<strong>" + num + "</strong>");
				}else{
					var a = this._build_a(num, num);
					aa.push(a);
				}
			}
			
			if(page < this.pageCount){
				var a = this._build_a(page + 1, "Next", this.options.nextClass);
				aa.push(a);
			}else{
				aa.push("<span class='" + this.options.nextClass + "'>Next</span>");
			}
			
			this.$ele.html(aa.join(""));
			this._bind_events();
		},
		
		_build_a: function(page, text, cls){
			cls = cls || '';
			return ["<a page='", page, "' class='", cls, "' href='javascript:;'>", text, "</a>"].join("");			
		}
	};
})(jQuery);